package com.stuManager.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stuManager.dao.UserDao;
import com.stuManager.model.CommonResponseModel;
import com.stuManager.model.User;
import com.stuManager.service.StudentService;
import com.stuManager.util.CookiesUtil;
import com.stuManager.util.ReadPostBodyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/*
    StudentListServlet
    学生列表接口
 */
@WebServlet(name = "StudentListServlet", value = "/studentList")
public class StudentListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CommonResponseModel m = new CommonResponseModel();
        //先获取cookie信息鉴权
        Cookie token = CookiesUtil.getCookieByName(request, "token");
        if (token == null) {
            m.setErrorCode(1);
            m.setMessage("用户未授权");
        }
        else {
            //获取一个service来处理业务
            StudentService service = new StudentService();
            //获取post参数
            String requestBody = ReadPostBodyUtil.getPostData(request);
            JSONObject json = JSON.parseObject(requestBody);
            json.put("token", token.getValue());
            System.out.println("post body 参数"+ json);
            m = service.fetchStudentList(json);
        }
        String jsonString = JSON.toJSONString(m);
        System.out.println("返回数据\n" + jsonString);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
